<?php
require("simple_html_dom.php");
include "config.php";
Requests::register_autoloader();
header('Content-type: application/json');

if (isset($_GET["uid"])){
    $UID = $_GET["uid"];
} else {
    echo json_encode(array());
    die(0);
}

if (isset($_GET["page"])){
    $page = $_GET["page"];
} else {
    $page = "1";
}

if (!isset($_GET["type"])){
    $url = "http://www.jianshu.com/u/". $UID ."?page=". $page;
} elseif ($_GET["type"] == "u"){
    $url = "http://www.jianshu.com/u/". $UID ."?page=". $page;
} elseif ($_GET["type"] == "nb"){
    if (!isset($_GET["id"])){
        echo json_encode(array());
        die(0);
    }
    $url = "http://www.jianshu.com/nb/". $_GET["id"] ."?page=". $page;
}

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
$response = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) == 301){
    echo json_encode($r);
    die(0);
}
curl_close($ch);

$html = new simple_html_dom();
$html->load($response);
$articles = array();
foreach ($html->find("ul.note-list li") as $a){
    $img = $a->find("a.wrap-img img");
    if ($img) {
        $imgSrc = $img[0]->src;
    } else {
        $imgSrc = $DEFAULT_IMG;
    }
    array_push($articles, array(
        "contentUrl" => $HOST."article_detail.php?id=".substr($a->find("a.title")[0]->href, 3),
        "title" => $a->find("a.title")[0]->plaintext,
        "summary" => trim($a->find("p.abstract")[0]->plaintext),
        "view" => (int)trim($a->find("div.meta a")[0]->plaintext),
        "imgSrc" => $imgSrc,
        "time" => $a->find("span.time")[0]->{'data-shared-at'}
    ));
}
echo json_encode($articles);

?>